package com.memory.filedownload.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * ClassName: DoFileDownload_1
 * Package: com.memory.filedownload.controller
 * Description:
 *
 * @Author Memory
 * @Create 2024/12/24 13:26
 * @Version 1.0
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello World";
    }

    /**
     * 客户端下载
     *
     * @param response response
     * @return HttpServletResponse
     */
    @PostMapping("/download_1")
    public HttpServletResponse doFileDownload_1(HttpServletResponse response) {
        // 本地文件路径
        String filePath = System.getProperty("user.dir") + "/src/main/resources/license/new.png";
        // 下载时文件名（客户端保存时看到的文件名）
        String downloadFileName = "download_1.png";
        try (
                // 使用缓冲输入流读取本地文件
                BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)));
                // 使用HttpServletResponse的输出流将文件发送给客户端
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())
        ) {
            // 设置响应头
            response.setContentType("image/png"); // 根据文件类型设置正确的MIME类型
            response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
            // 读取文件内容并写入响应输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            // 刷新输出流以确保所有数据都被发送
            outputStream.flush();
        } catch (IOException e) {
            // 处理异常，例如记录日志或返回错误响应
            throw new RuntimeException("文件下载失败", e);
        }
        return response;
    }

    /**
     * 本地文件下载
     */
    @PostMapping("/download_2")
    public void doFileDownload_2(HttpServletResponse response) {
        // 下载本地文件
        int byteRead = 0;
        int byteSum = 0;
        try {
            // 本地文件路径
            FileInputStream inputStream = new FileInputStream(System.getProperty("user.dir") + "/src/main/resources/license/new.png");
            // 指定下载路径
            File filePath = new File("D:\\Project\\tellhow\\file-download\\src\\main\\resources");
            if (!filePath.exists()) filePath.mkdirs();
            String filename = "download_2.png";
            OutputStream outputStream = Files.newOutputStream(Paths.get(filePath.getPath() + "\\" + filename));
            // 读取文件
            byte[] buff = new byte[1024];
            while ((byteRead = inputStream.read(buff)) >= 0) {
                byteSum += byteRead;
                System.out.println(byteSum);
                outputStream.write(buff, 0, byteRead);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 网络文件下载
     */
    @PostMapping("/download_3")
    public void doFileDownload_3(HttpServletResponse response) {
        // 下载网络文件
        int byteRead = 0;
        int byteSum = 0;
        URLConnection con = null;
        try {
            // 网络文件路径
            URL url = new URL("https://foruda.gitee.com/avatar/1696169390391843074/10920353_deng-2022_1696169390.png");
            con = url.openConnection();
            InputStream inputStream = con.getInputStream();
            con.setConnectTimeout(20 * 1000);
            // 指定下载路径
            File filePath = new File("D:\\Project\\tellhow\\file-download\\src\\main\\resources");
            if (!filePath.exists()) filePath.mkdirs();
            String filename = "download_3.png";
            OutputStream outputStream = Files.newOutputStream(Paths.get(filePath.getPath() + "\\" + filename));
            // 读取文件
            byte[] buff = new byte[1024];
            while ((byteRead = inputStream.read(buff)) >= 0) {
                byteSum += byteRead;
                System.out.println(byteSum);
                outputStream.write(buff, 0, byteRead);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
